<?php

/**
 * @name OrderController
 * @desc 控制器(商品订单 order_pro 表)
 */
class OrderController extends AdminCommonController
{
    //订单列表
    public function listAction(){
        $params = $this->jsonData();

        $row = $params['pageSize'] ?? 12;
        $page = $params['page'] ?? 1;

        $cond = [];
        if(isset($params['moble']) && $params['moble']){
            $cond['u.moble'] = trim($params['moble']);
        }
        if(isset($params['user_id']) && $params['user_id']>0){
            $cond['o.user_id'] = trim($params['user_id']);
        }
        if(isset($params['date_s']) && $params['date_s'] != ''){
            $cond['o.pay_time#>='] = $params['date_s'];
        }
        if(isset($params['date_e']) && $params['date_e'] != ''){
            $cond['o.pay_time#<'] = $params['date_e'];
        }
        if(isset($params['nick_name']) && $params['nick_name'] != ''){
            $cond['u.nick_name#like'] = trim($params['nick_name']). '%';
        }
        if(isset($params['order_no']) && $params['order_no'] != ''){
            $cond['o.order_no'] = trim($params['order_no']);
        }
        if(isset($params['status']) && !empty($params['status'])){
            $cond['o.status#in'] = $params['status'];
        }

        //非超级管理员
        $adminInfo = AdminModel::getSingleton()->find(['admin_id'=> $this->admin_info['admin_id']], 'admin_type,moble,user_id');
        if($adminInfo['admin_type']==1 || $adminInfo['admin_type'] == 2){
            $userInfo = UserModel::getSingleton()->find(['user_id'=> $adminInfo['user_id']], 'shop_id');
            $cond['o.shop_id'] = $userInfo['shop_id'];
        }

        $orderModel = OrderModel::getSingleton();
        $list = $orderModel->db
            ->field('o.*, u.moble, u.nick_name')
            ->alias('o')
            ->join(['user', 'u'], ['o.user_id'=> 'u.user_id'], 'left join')
            ->where_c($cond)
            ->order('o.order_id desc')
            ->limit(($page - 1) * $row, $row)
            ->select();

        $total = $orderModel->db
            ->alias('o')
            ->join(['user', 'u'], ['o.user_id'=> 'u.user_id'], 'left join')
            ->where_c($cond)
            ->count();

        $orderProductModel = OrderProductSpecsModel::getSingleton();
        foreach($list as &$val){
            $val['product_list'] = $orderProductModel->findAll(['order_id'=> $val['order_id']]);
            foreach ($val['product_list'] as &$vv){
                $vv['product_name_full'] = $vv['product_name']. ' '. $vv['spec_name_full'];
            }
            $val['status_text'] = OrderModel::$statusText[$val['status']];
        }

        $data = [
            'list' => $list,
            'total' => intval($total),
            'current'   => intval($page),
            'pageSize'  => intval($row),
            'page'  => intval($page),
            'pageNum'   => ceil($total/$row)
        ];

        $this->ajaxReturn(0, '', $data);
    }

    //详情
    public function detailAction(){
        $params = $this->jsonData();

        if(!isset($params['product_no']) || !intval($params['product_no'])){
            $this->ajaxReturn(400, '必须传递订单编号');
        }

        $orderProModel = OrderProModel::getSingleton();
        $detail = $orderProModel->find(['product_no'=> $params['product_no']]);
        if(!$detail){
            $this->ajaxReturn(400, '订单不存在');
        }
        if($detail['is_delete'] == 1){
            $this->ajaxReturn(400, '订单已删除');
        }

        $orderProductModel = OrderProductModel::getSingleton();
        $detail['product_list'] = $orderProductModel->findAll(['order_id'=> $detail['order_id']]);
        $detail['status_text'] = OrderProModel::$statusText[$detail['status']];

        $this->ajaxReturn(0, 'success', $detail);
    }

    //edit
    public function editAction(){
        $params = $this->jsonData();

        $rule = [
            'order_id'    => 'require',
            'status'     => 'integer',
        ];
        $msg = [
            'order_id.require'    => '未获取到订单ID',
            'status.integer'   => '订单状态不正确'
        ];
        $validate = new \Vendor\Kvalidate($rule,$msg);
        if(!$validate->check($params)){
            $this->ajaxReturn(400, $validate->getError());
        }

        $orderModel = OrderModel::getSingleton();
        $order_id = $params['order_id'];
        unset($params['order_id']);

        $cond = ['order_id'=> $order_id];
        if(is_array($order_id)){

            try {
                \Vendor\DB::startTrans();

                foreach($order_id as $val){
                    $thisOrder = $orderModel->find(['order_id'=> $val]);
                    if($params['status'] == 2 && $thisOrder['status']!=1){
                        \Vendor\DB::rollback();
                        $this->ajaxReturn(400, '所选的订单中含有非已支付状态的订单，请重新筛选。');
                    }
                    if($params['status'] == 3 && $thisOrder['status']!=2){
                        \Vendor\DB::rollback();
                        $this->ajaxReturn(400, '所选的订单中含有非已配送状态的订单，请重新筛选。');
                    }
                    if(!$orderModel->update($cond, $params)){
                        \Vendor\DB::rollback();
                        $this->ajaxReturn(400, '操作失败');
                    }
                }

                \Vendor\DB::commit();
            }catch(Exception $e){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, $e->getMessage());
            }
        }else {

            $description = '['.OrderModel::$statusText[$params['status']].']';
            //不同意退款
            if($params['status'] == 8){
                if(!$params['text']){
                    $this->ajaxReturn(400, '必须输入原因');
                }
                $description = '['.OrderModel::$statusText[$params['status']].']'.'店铺不同意退款，原因：'.$params['text'];
                unset($params['text']);
            }

            try{
                \Vendor\DB::startTrans();

                //修改订单
                $orderInfo = $orderModel->find(['order_id'=> $order_id]);
                if($orderInfo['status'] == $params['status']){
                    \Vendor\DB::rollback();
                    $this->ajaxReturn(400, '请勿重复修改');
                }

                //下单人信息
                $userModel = UserModel::getSingleton();
                $userInfo = $userModel->find(['user_id'=> $orderInfo['user_id']]);

                //已完成
                if($params['status'] == 3){
                    $params['status_three_time'] = time();  //完成时间
                }
                if(!$orderModel->update($cond, $params)){
                    \Vendor\DB::rollback();
                    $this->ajaxReturn(400, '操作失败');
                }

                //订单记录
                $orderLogModel = OrderLogModel::getSingleton();
                if(!$orderLogModel->add([
                    'order_id'  => $orderInfo['order_id'],
                    'order_no'  => $orderInfo['order_no'],
                    'user_id'   => $orderInfo['user_id'],
                    'shop_id'   => $orderInfo['shop_id'],
                    'status'    => $params['status'],
                    'description'   => $description,
                    'create_time'   => time()
                ])){
                    \Vendor\DB::rollback();
                    $this->ajaxReturn(400, '操作失败', $orderLogModel->errMsg);
                }

                //如果同意退款则恢复库存
                if($params['status'] == 9){
                    $orderProductList = OrderProductSpecsModel::getSingleton()->findAll(['order_id'=> $order_id]);
                    $shopProductSpecs = ShopProductSpecsModel::getSingleton();
                    foreach ($orderProductList as $val){
                        $where = ['shop_id'=> $val['shop_id'], 'spec_id'=> $val['spec_id']];
                        if(!$shopProductSpecs->setInc($where, 'shop_spec_stock', $val['buy_num'])){
                            \Vendor\DB::rollback();
                            $this->ajaxReturn(400, '操作失败');
                        }
                    }
                }

                //已完成更新销量 和 赠送积分
                if($params['status'] == 3){
                    $orderProductList = OrderProductSpecsModel::getSingleton()->findAll(['order_id'=> $order_id]);
                    $shopProductSpecs = ShopProductSpecsModel::getSingleton();
                    foreach ($orderProductList as $val){
                        $where = ['shop_id'=> $val['shop_id'], 'spec_id'=> $val['spec_id']];
                        if(!$shopProductSpecs->setInc($where, 'shop_sale_num', $val['buy_num'])){
                            \Vendor\DB::rollback();
                            $this->ajaxReturn(400, '操作失败');
                        }
                    }

                    /**
                     * 赠送积分
                     */
                    if($userInfo['user_id'] != 1){
                        //推荐人信息（直营奖励）
                        $onlineShopUserInfo = $userModel->find(['user_id'=> $userInfo['refer_user_id']]);
                        //推荐人的推荐人信息（网店奖励）
                        $prevOnlineShopUserInfo = $userModel->find(['user_id'=> $onlineShopUserInfo['refer_user_id']]);
                        //实体店用户信息
                        $shopInfo = ShopModel::getSingleton()->find(['shop_id'=> $userInfo['shop_user_id']], 'user_id');
                        $offlineShopUserInfo = $userModel->find(['user_id'=> $shopInfo['user_id']]);

                        $rewardLogModel = RewardLogModel::getSingleton();
                        //直营奖励比例
                        $o_ratio = $rewardLogModel->getRatio(time(), $onlineShopUserInfo['user_id']);
                        //直营奖励
                        $data = [
                            'type'          => 1,
                            'user_id'       => $onlineShopUserInfo['user_id'],
                            'from_user_id'  => $userInfo['user_id'],
                            'from_user_type'    => $userInfo['user_type'],
                            'order_id'      => $orderInfo['order_id'],
                            'point'         => $orderInfo['kpi_point'] * $o_ratio,
                            'point_base'    => $orderInfo['kpi_point'],
                            'money'         => $orderInfo['total_money'],
                            'ratio'         => $o_ratio,
                            'description'   => '直营奖励',
                            'status'        => 1,
                        ];
                        if(!$rewardLogModel->add($data)){
                            \Vendor\DB::rollback();
                            $this->ajaxReturn(400, '直营奖励失败。', $rewardLogModel->errMsg);
                        }
                        //网店奖励(如果上级没上级，这个奖励就给自己)
                        $ratio = 0.05;
                        if(!$prevOnlineShopUserInfo){
                            $prevOnlineShopUserInfo = $onlineShopUserInfo;
                            $prevOnlineShopUserRatio = 0;
                            $point = $orderInfo['kpi_point'] * $ratio;
                            $description = '实体店直推，获得%5奖励';
                        } else {
                            //判断比例是否超越
                            $prevOnlineShopUserRatio = $rewardLogModel->getRatio(time(), $prevOnlineShopUserInfo['user_id']);
                            if($prevOnlineShopUserRatio>=$o_ratio){
                                $description = '正常获得奖励';
                                $point = $orderInfo['kpi_point'] * $ratio;
                            }else {
                                $description = '提成比例被超越，无法获得提成，自身：'.$prevOnlineShopUserRatio.'，下级网店：'.$o_ratio;
                                $point = 0;
                            }
                        }
                        $data = [
                            'type'          => 2,
                            'user_id'       => $prevOnlineShopUserInfo['user_id'],
                            'from_user_id'  => $userInfo['user_id'],
                            'from_user_type'    => $userInfo['user_type'],
                            'order_id'      => $orderInfo['order_id'],
                            'point'         => $point,
                            'point_base'    => $orderInfo['kpi_point'],
                            'money'         => $orderInfo['total_money'],
                            'ratio'         => $ratio,
                            'self_ratio'    => $prevOnlineShopUserRatio,
                            'o_ratio' => $o_ratio,
                            'o_user_id'    => $onlineShopUserInfo['user_id'],
                            'description'   => $description,
                            'status'        => 1,
                        ];
                        if(!$rewardLogModel->add($data)){
                            \Vendor\DB::rollback();
                            $this->ajaxReturn(400, '网店奖励失败。', $rewardLogModel->errMsg);
                        }
                        //实体店奖励
                        $ratio = 0.15;
                        //判断比例是否超越
                        $offlineShopUserRatio = $rewardLogModel->getRatio(time(), $offlineShopUserInfo['user_id']);
                        if($offlineShopUserRatio>=$o_ratio){
                            $description = '正常获得奖励';
                            $point = $orderInfo['kpi_point'] * $ratio;
                        }else {
                            $description = '提成比例被超越，无法获得提成';
                            $point = 0;
                        }
                        $data = [
                            'type'          => 3,
                            'user_id'       => $offlineShopUserInfo['user_id'],
                            'from_user_id'  => $userInfo['user_id'],
                            'from_user_type'    => $userInfo['user_type'],
                            'order_id'      => $orderInfo['order_id'],
                            'point'         => $point,
                            'point_base'    => $orderInfo['kpi_point'],
                            'money'         => $orderInfo['total_money'],
                            'ratio'         => $ratio,
                            'self_ratio'    => $offlineShopUserRatio,
                            'o_ratio'       => $o_ratio,
                            'o_user_id'     => $onlineShopUserInfo['user_id'],
                            'description'   => $description,
                            'status'        => 1,
                        ];
                        if(!$rewardLogModel->add($data)){
                            \Vendor\DB::rollback();
                            $this->ajaxReturn(400, '实体店奖励失败。', $rewardLogModel->errMsg);
                        }
                    }
                }

                \Vendor\DB::commit();
            }catch(Exception $e){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '下单失败，请返回重试!', $e->getMessage());
            }


        }

        $this->ajaxReturn(0, '操作成功');
    }

}
